package com.alex.server.service.impl;

import com.alex.server.domain.File;
import com.alex.server.dto.FileDto;
import com.alex.server.dto.PageDto;
import com.alex.server.mapper.FileMapper;
import com.alex.server.service.IFileService;
import com.alex.server.util.CopyUtil;
import com.alex.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class FileServiceImpl implements IFileService {

    @Autowired
    private FileMapper mapper;

    @Override
    public PageDto list(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        List<File> fileList = mapper.selectByExample(null);
        PageInfo<File> pageInfo = new PageInfo<>(fileList);
        pageDto.setTotal(pageInfo.getTotal());
        List<FileDto> fileDtoList = CopyUtil.copyList(fileList, FileDto.class);
        pageDto.setList(fileDtoList);
        return pageDto;
    }

    @Override
    public void save(FileDto fileDto) {
        File file = CopyUtil.copy(fileDto, File.class);
        if (StringUtils.isEmpty(fileDto.getId())){
            this.insert(file);
        } else {
            this.update(file);
        }
    }

    @Override
    public void insert(File file) {
        file.setId(UuidUtil.getShortUuid());
        mapper.insert(file);
    }

    @Override
    public void update(File file) {
        mapper.updateByPrimaryKey(file);
    }

    @Override
    public void delete(String id) {
        mapper.deleteByPrimaryKey(id);
    }

}